//Internationalization support functions
//created by bfchen 2005-09-02

#include "stdafx.h"
#include ".\i18n.h"

CI18N::CI18N(void)
{
}

CI18N::~CI18N(void)
{
}

wchar_t* CI18N::MBCS2Unicode(const char* inputString)
{
	UINT nCodePage = CP_ACP; //Local code page (ANSI)
	int nLength=MultiByteToWideChar(nCodePage,0,inputString,-1,NULL,0);
	wchar_t* pBuffer = new wchar_t[nLength+1];
	MultiByteToWideChar(nCodePage,0,inputString,-1,pBuffer,nLength);
	pBuffer[nLength]=0;
	return pBuffer;
}

char* CI18N::Unicode2MBCS(const wchar_t* inputString)
{
	UINT nCodePage = CP_ACP; //Local code page
	int nLength=WideCharToMultiByte(nCodePage,0,inputString,-1,NULL,0,NULL,NULL);
	char* pBuffer=new char[nLength+1];
	WideCharToMultiByte(nCodePage,0,inputString,-1,pBuffer,nLength,NULL,NULL);
	pBuffer[nLength]=0;
	return pBuffer;
}

char* CI18N::MBCS2UTF8(const char* inputString)
{
	wchar_t* tempBuff = MBCS2Unicode(inputString);
	char* retBuff = Unicode2UTF8(tempBuff);
	delete[] tempBuff;
	return retBuff;
}

char* CI18N::Unicode2UTF8(const wchar_t* inputString)
{
	UINT nCodePage = CP_UTF8; //Local code page
	int nLength = WideCharToMultiByte(nCodePage,0,inputString,-1,NULL,0,NULL,NULL);
	char* pBuffer= new char[nLength+1];
	WideCharToMultiByte(nCodePage,0,inputString,-1,pBuffer,nLength,NULL,NULL);
	pBuffer[nLength]=0;
	return pBuffer;
}

char* CI18N::TCHAR2UTF8(LPCTSTR inputString)
{
#ifdef _UNICODE
	return Unicode2UTF8(inputString);
#else
	return MBCS2UTF8(inputString);
#endif
}


TCHAR* CI18N::HTMLEscapeA(const char* inputString)
{
	static char NUMS[]= {'0','1','2','3','4','5','6','7','8',
		'9','A','B','C','D','E','F'};
	int nLen = strlen(inputString);
	char* pBuffer = new char[nLen *3+1];

	char* pSource = (char*)inputString;
	char* pDest = pBuffer;
	while(*pSource)
	{	
		char c = *pSource;
		if( (c >= '0' && c <= '9')||
			(c >= 'a' && c <= 'z')||
			(c >= 'A' && c <= 'Z'))
		{
			*pDest = c;
			pDest++;//do nothing
		}
		else
		{
			//memmove(p+3,p+1,strlen(p+1)+1);
			*pDest = '%'; pDest++;
			*(pDest) = NUMS[(c & 0xf0)>>4]; pDest++;
			*(pDest) = NUMS[ c & 0x0f]; pDest++;	
		}
		pSource++;
	}
	*pDest = 0;pDest++;
	
#ifdef _UNICODE
	wchar_t* pRet = MBCS2Unicode(pBuffer);
#else
	char* pRet = new char[pDest - pBuffer];
	strcpy(pRet,pBuffer);
#endif

	delete[] pBuffer;
	return pRet;
}

TCHAR* CI18N::HTMLEscapeW(const wchar_t* inputString)
{
	char* buff = Unicode2MBCS(inputString);
	TCHAR* pRet = HTMLEscapeA(buff);
	delete[] buff;
	return pRet;
}

TCHAR* CI18N::HTMLEscape(LPCTSTR inputString)
{
#ifdef _UNICODE
	return HTMLEscapeW((LPCWSTR)inputString);
#else
	return HTMLEscapeA(inputString);
#endif
}

